// 本文件实现简单的who命令，在控制台列出当前登录的用户信息。
// 已经能够正确读到utmp数据结构
// 缺点：只显示了基本数据类型的信息，高级数据类型比如时间、进程ID可以查阅手册完善

#include<stdio.h>
#include<stdlib.h>
#include<utmp.h>
#include<fcntl.h>// File open/read
#include<unistd.h>// File close

#define SHOWHOST

void show_info( struct utmp *utbufp );

int main()
{
    struct utmp current_record;// man 5 utmp, structure of utmp
    int utmpfd;// utmp file descriptor
    int reclen = sizeof(current_record);

    // open utmp file
    if (-1 == (utmpfd = open(UTMP_FILE, O_RDONLY)))
    {
        perror(UTMP_FILE);// UTMP_FILE is in utmp.h
        exit(1);
    }

    while (reclen == read(utmpfd, &current_record, reclen))
    {
        show_info(&current_record);// read the utmp record & show it
    }

    close(utmpfd);

    return 0;
}

void show_info( struct utmp *utbufp )
{
    printf("%-8.8s", utbufp->ut_user);  // Username
    printf(" ");

    printf("%-8.8s", utbufp->ut_line);  // Devide name of tty...
    printf(" ");

    printf("%s", utbufp->ut_host);  // Hostname for remote login
    printf("\n");
}
